<%@ page import="POJO.*" %>
<%@ page import="DB.*" %>

<%

            UserManager db = new UserManager(DBInfo.getConnection());
            TripManager db2 = new TripManager(db.conn);
            ContentContainerManager db3 = new ContentContainerManager(db.conn);
            User u = (User) session.getAttribute("user");
            u.GetInfo();
            if (request.getParameter("page") == null || !request.getParameter("page").equals("trip") || request.getParameter("tripid") == null || u == null) {
%>

<h2 class="nice">Unauthorized entrance.</h2>

<%  } else if (!db.isConnected() || !db2.isConnected()) {
                out.print("<h2 class=\"nice\">No connection with the database.</h2>");
            } else {
                if (u.username == null || !db2.isOwnerOf(Integer.parseInt(request.getParameter("tripid")), u.username)) {
                    out.print("<h2 class=\"nice\">You are not a owner of this trip.</h2>");
                } else {
                    int tripId = Integer.parseInt(request.getParameter("tripid"));
                    boolean removed = false;

                    if (request.getMethod().equals("POST") && request.getParameter("edit") != null && request.getParameter("edit").compareTo("true") == 0 && request.getMethod().equals("POST")) //nieuwe waarden zijn verstuurd
                    {
                        if (request.getParameter("remove") != null && request.getParameter("remove").compareTo("on") == 0) {
                            removed = db2.removeTrip(tripId);
                            if (removed) {
                                try {
                                    RSSCreator.createRSS();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                out.print("<h1 class = \"nice\">Trip removed.</h1>");
                            } else {
                                out.print("<h1 class = \"nice\">The trip is not completely removed, but will not be visible anymore. Please contact the webmaster.</h1>");
                            }
                        } else {
                            try {
                                RSSCreator.createRSS();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            String newName = request.getParameter("name");
                            String newBDate = request.getParameter("start");
                            String newEDate = request.getParameter("end");
                            if (newEDate.compareTo("") != 0) {
                                db2.changeEnd(tripId, newEDate);
                            }
                            if (newBDate.compareTo("") != 0) {
                                db2.changeStart(tripId, newBDate);
                            }
                            db2.changeTripName(tripId, newName);
                        }
                    }

                    if (request.getParameter("removeid") != null) {
                        db3.deleteContentContainer(Integer.parseInt(request.getParameter("removeid")));
                    }
                    if (!removed) {
%>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="date.js"></script>
<script type="text/javascript" src="datePicker.js"></script>
<script type="text/javascript" charset="utf-8">
    $(function()
    {
        Date.format = 'yyyy/mm/dd';
        $('.date-pick').datePicker({clickInput:true});        
        $('.date-pick').dpSetStartDate('1990/01/01');
        
        $('#start').bind(
        'dpClosed',
        function(e, selectedDates)
        {
            var d = selectedDates[0];
            if (d) {
                d = new Date(d);
                $('#end').dpSetStartDate(d.addDays(1).asString());
            }
        }
    );
        $('#ende').bind(
        'dpClosed',
        function(e, selectedDates)
        {
            var d = selectedDates[0];
            if (d) {
                d = new Date(d);
                $('#start').dpSetEndDate(d.addDays(-1).asString());
            }
        }
    );
        
    });
    
    function checkTrip(form) {
        if (form.tripname.value.length < 3) {
            alert("Trip name should be at least 3 characters long!");
            form.tripname.focus();
            return false;
        }
        else if (form.start.value.match(/^\d{4}\/\d{2}\/\d{2}$/) != form.start.value || form.end.value.match(/^\d{4}\/\d{2}\/\d{2}$/) != form.end.value) {
            alert("Both dates should be filled in and valid!\nValid format: yyyy/mm/dd");
            form.start.focus();
            return false;
        }
        else if (form.start.value > form.end.value) {
            alert("Start date should be before (or equal to) end date!");
            form.start.focus();
            return false;
        }
        else if (form.remove.checked == true)
            return confirm("Are you sure you want to remove this trip? This cannot be undone!");
        else
            return true;
    }
</script>

<%
        out.print("<h1 class=\"nice\">" + db2.getTripName(tripId) + "</h1>");
        out.print("<div style=\"text-align:left;\"><form action=\"index.jsp?page=trip&amp;tripid=" + tripId + "&amp;edit=true\" method=\"post\" onsubmit =\"return checkTrip(this)\" ><table class=\"nice\" width = \"100%\" style=\"text-align:left;\">");
        out.print("<tr><td class=\"b\">Name:</td><td>&nbsp;&nbsp;&nbsp;<input size=\"35\" type=\"text\" name=\"tripname\" value=\"" + db2.getTripName(tripId) + "\"/></td></tr>");
        out.print("<tr><td class=\"b\" colspan=\"2\"><label for=\"start\">Start Date:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input size=\"50\" type=\"text\" class=\"date-pick\" id=\"start\" name=\"start\" value=\"" + db2.getStart(tripId) + "\"/></td></tr>");
        out.print("<tr><td class=\"b\" colspan=\"2\"><label for=\"end\">End Date:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input size=\"50\" type=\"text\" class=\"date-pick\" id=\"end\" name=\"end\" value=\"" + db2.getEnd(tripId) + "\"/></td></tr>");
        out.print("<tr><td class=\"b\">Remove this trip</td><td><input type=\"checkbox\" name=\"remove\" /></td></tr>");
        out.print("<tr><td colspan=\"2\" align=\"center\"><br /><input type=\"submit\" value=\"Change Trip Data\" /></td></tr></table></form></div>");

        Maps map = new Maps();
        out.println(map.selectStop(tripId, u, db.conn));
%>

<script type="text/javascript">
    var xmlHttp;
    
    function showAddStopForm()
    {        
        xmlHttp=GetXmlHttpObject();
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readyState == 4)
            {                
                document.getElementById("addStop").innerHTML = xmlHttp.responseText;
                $(function()
                {
                    Date.format = 'yyyy/mm/dd';
                    $('.date-pick').datePicker({clickInput:true});        
                    $('.date-pick').dpSetStartDate('1990/01/01');
                });
            }
        } 
        xmlHttp.open("POST", "addStop?tripid=<% out.print(tripId);%>", true);
        xmlHttp.send("");
        setTimeout('selectInitialize()', 500);
    }
    
    function GetXmlHttpObject()
    {
        var xmlHttp=null;
        try
        {
            xmlHttp=new XMLHttpRequest();
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e)
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return xmlHttp;
    }
</script>



<%

        if (request.getParameter("ownerRemoval") != null) //nieuwe waarden zijn verstuurd
        {
            String owner = request.getParameter("ownerRemoval");
            db2.removeOwnership(tripId, owner);
        }

        if (request.getParameter("ownerRequests") != null && request.getParameter("ownerRequests").compareTo("true") == 0 && request.getMethod().equals("POST")) //nieuwe waarden zijn verstuurd
        {
            String[] ownerRequests = db2.getOwnershipRequestsByTripID(tripId);
            for (int i = 0; ownerRequests != null && i < ownerRequests.length; ++i) {
                if (request.getParameter(ownerRequests[i]) != null && request.getParameter(ownerRequests[i]).compareTo("accept") == 0) {
                    db2.confirmOwnership(tripId, ownerRequests[i]);
                } else if (request.getParameter(ownerRequests[i]) != null && request.getParameter(ownerRequests[i]).compareTo("reject") == 0) {
                    db2.declineOwnership(tripId, ownerRequests[i]);
                }
            }
        }

        String[] owners = db2.getOwners(tripId);
        out.print("<div><table width=\"100%\" class=\"nice\" style=\"text-align:left;\"><tr><td colspan=\"2\" class=\"b\">Owners:</td></tr>");
        for (int i = 0; owners != null && i < owners.length; ++i) {
            out.print("<tr><td style=\"text-align:left;\">&nbsp;&nbsp;&nbsp;&nbsp;<a class=\"nice\"  href=\"index.jsp?page=profile&amp;user=" + owners[i] + "\">" + owners[i] + "</a></td><td style=\"width: 8em;\"><a class = \"nice\" href=\"index.jsp?page=trip&amp;tripid=" + tripId + "&amp;ownerRemoval=" + owners[i] + "\">[X]</a></td></tr>");
        }
        out.print("</table></div>");

        String[] ownerRequests = db2.getOwnershipRequestsByTripID(tripId);
        if (ownerRequests != null && ownerRequests.length != 0) {
            out.print("<div><form action=\"index.jsp?page=trip&amp;tripid=" + tripId + "&amp;ownerRequests=true\" method=\"post\"><table width=\"100%\" class=\"nice\" style=\"text-align:left;\"><tr><td colspan=\"2\" class=\"b\">Ownership requests:</td></tr>");
            for (int i = 0; ownerRequests != null && i < ownerRequests.length; ++i) {
                out.print("<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;<a class=\"nice\"  href=\"index.jsp?page=profile&amp;user=" + ownerRequests[i] + "\">" + ownerRequests[i] + "</a></td>" +
                        "<td><input type=\"radio\" name=\"" + ownerRequests[i] + "\" value=\"accept\"/> Accept <input type=\"radio\" name=\"" + ownerRequests[i] + "\" value=\"reject\"/> Reject</td></tr>");
            }
            out.print("<tr><td colspan=\"2\" align=\"center\"><br /><br /><input type=\"submit\" value=\"Process requests\" /></td></tr></table></form></div>");
        }
%>

<%
        if (request.getParameter("addStop") != null && request.getParameter("addStop").compareTo("true") == 0 && request.getMethod().equals("POST")) //nieuwe waarden zijn verstuurd
        {
            String north = request.getParameter("north");
            String east = request.getParameter("east");
            String date = request.getParameter("arrival");
            String viewable = request.getParameter("view");
            String location = request.getParameter("location");
            if (east != "" && north != "" && location != "") {
                db3.addContentContainer(u.username, tripId, viewable, date, Double.parseDouble(north), Double.parseDouble(east), location);
            }
        }

        int[] containers = db3.getAllContentContainersOfTripForOwners(tripId);
        out.print("<div><table width=\"100%\" class=\"nice\" style=\"text-align:left;\"><tr><td colspan=\"2\" class=\"b\">Stops:</td></tr>");
        /*  for (int i = 0; containers != null && i < containers.length; ++i) {
        out.print("<tr><td style=\"text-align:left;\">&nbsp;&nbsp;&nbsp;&nbsp;<a class=\"nice\"  href=\"index.jsp?page=triplocation&amp;containerid=" + containers[i] + "\">Stop nr. " + (containers.length - i) + " (" + db3.getArrival(containers[i]) + ")</a></td><td style=\"width: 8em;\"><a class = \"nice\" href=\"index.jsp?page=trip&amp;tripid=" + tripId + "&amp;containerRemoval=" + containers[i] + "\">[X]</a></td></tr>");
        }*/
        out.print("<tr><td colspan=\"2\"><div  id=\"map_canvas\" style=\"height: 300px; width:100%;\"></div></td></tr>");
        out.print("<tr><td style=\"text-align:left;\">&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"anice\" onclick=\"showAddStopForm();\">Add a new stop</span></td><td></td></tr>");
        out.print("<tr><td colspan=\"2\">");
%>

<div id="addStop" style="position:relative;top:8px;left:20px;">
</div>

<%
                        out.print("</td></tr></table></div>");

                        out.print(map.tripMap(tripId, (User) session.getAttribute("user"), true));
                    } // if !removed

                }
            }%>